<template>
  <div id="add-customers" class="container">
    <div class="basic">
      <div class="content">
        <el-form ref="form" :inline="true" :model="form" :rules="rules">
          <el-form-item label="客户姓名" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入客户姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone1">
            <el-input
              maxlength="11"
              v-model.trim="form.phone1"
              placeholder="请输入客户电话"
              clearable
              type="number"
              oninput="if (value.length > 11) value = value.slice(0, 11);"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话2" prop="phone2">
            <el-input
              maxlength="11"
              v-model.trim="form.phone2"
              placeholder="请输入客户电话"
              clearable
              type="number"
              oninput="if (value.length > 11) value = value.slice(0, 11);"
            ></el-input>
          </el-form-item>
          <el-form-item label="生日">
            <el-date-picker
              v-model="form.birthday"
              placeholder="请选择生日日期"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model.trim="form.age"
              placeholder="请输入客户年龄"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              :maxLength="3"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="form.gender" placeholder="请选择性别" clearable>
              <el-option
                v-for="item in dictionaries.gender"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="婚否">
            <el-select
              v-model="form.marriage"
              placeholder="请选择婚否"
              clearable
            >
              <el-option
                v-for="item in dictionaries.marriage"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="身高（CM）" prop="tall">
            <el-input
              v-model.trim="form.tall"
              placeholder="请输入客户身高（CM）"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              :maxLength="3"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="体重（KG）" prop="weight">
            <el-input
              oninput="value=value.replace(/[^0-9.]/g,'')"
              :maxLength="3"
              v-model.number="form.weight"
              placeholder="请输入客户体重（KG）"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="地区" :prop="addressValueState">
            <el-cascader
              :options="addressOptions"
              v-model="form.addressValue"
              @change="onChangeAddress"
              filterable
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="入线方式" v-if="type != 'edit'" prop="userDitch">
            <el-select
              v-model="form.userDitch"
              filterable
              placeholder="选择入线方式"
              clearable
            >
              <el-option
                v-for="item in line"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
           <el-form-item label="详细地址" v-if="type != 'edit'">
            <el-input
              maxlength="52"
              v-model="form.detailedAddress"
              placeholder="请输入详细地址"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="来源平台"
            v-if="type != 'edit'"
            prop="platformId"
          >
            <el-select
              v-model="form.platformId"
              placeholder="请选择来源平台"
              filterable
              clearable
            >
              <el-option
                v-for="item in platformList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="所属类目"
            v-if="type != 'edit'"
            prop="categoryId"
          >
            <el-cascader
              v-model="form.categoryId"
              :options="categoryList"
              :props="{
                checkStrictly: true,
                label: 'categoryName',
                value: 'id',
                children: 'children',
              }"
              clearable
              filterable
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="客户意向"
            v-if="type != 'edit'"
            prop="userIntention"
          >
            <el-select
              v-model="form.userIntention"
              filterable
              placeholder="选择客户意向"
            >
              <el-option
                v-for="item in dictionaries.customer_intention"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户等级" v-if="type != 'edit'" prop="userLevel">
            <el-select
              v-model="form.userLevel"
              filterable
              placeholder="选择客户等级"
            >
              <el-option
                v-for="item in dictionaries.customer_level"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="门店" v-if="type != 'edit'">
            <el-input
              maxlength="52"
              v-model="form.gateSentry"
              placeholder="请输入门店"
            >
            </el-input>
          </el-form-item>
            <el-form-item label="资源时间"  v-if="type != 'edit'">
             <el-date-picker
              v-model="form.ditchTimeStr"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="btn">
      <el-button @click="submitForm('cancel')">取消</el-button>
      <el-button type="primary" @click="submitForm('form')">确定</el-button>
      <!-- <el-button v-if="type != 'edit'" type="primary" @click="preserveEvent(1)"
        >保存并添加订单</el-button
      > -->
    </div>
  </div>
</template>

<script>
import addressData from '@/components/addressData.js'
import levelAddr from '@/components/levelAddr'
import $ from 'jquery'
// import func from "../../../vue-temp/vue-editor-bridge";
import { checkNumber } from '@/utils/rules.js'
export default {
  components: {
    levelAddr: levelAddr
  },
  props: {
    type: {
      type: String
    },
    clientObj: {
      type: Object
    },
    getDateList: {
      type: Function
    },
    dialogState: {
      type: Boolean
    }
  },
  data () {
    var isNumber = (rule, value, callback) => {
      if (!value) {
        console.log(value)
        if (this.type == 'edit') {
          callback()
        } else {
          return callback(new Error('不能为空'))
        }
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          console.log(typeof value, Number.isInteger(value), value)
          callback(new Error('请输入数字值'))
        } else {
          console.log(value)
          callback()
        }
      }, 500)
    }
    return {
      addressValueState: 'addressValue',
      addressOptions: [], // 地区 options
      pickerOptions: {
        shortcuts: [
          {
            text: '此刻',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          }
        ],
        disabledDate (time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      addressValue: [],
      form: {
        id: '',
        userName: '',
        categoryId: '', //   是 	int 	类目id
        name: '', // 	是 	string 	名称
        phone1: '', // 	是 	string 	联系电话1
        phone2: '', // 	否 	string 	联系电话2
        birthday: '', // 	否 	string 	生日（yyyy-MM-dd）
        age: '', // 	否 	int 	  年龄
        gender: '', // 	否 	string 	性别（字典分组：gender）
        marriage: '', // 	否 	string 	婚否（字典分组：marriage）
        tall: '', // 	否 	double 	身高（cm）
        weight: '', // 	否 	double 	重量（kg）
        provinceCode: '', // 	否 	string 	省级code
        cityCode: '', // 	否 	string 	市级code
        regionCode: '', 	 // 	否 	string 	地区级code
        userDitch: '', // 	是 	string 	入线方式（来源【入线渠道设定】）
        platformId: '', 	 // 	是 	int 	来源平台id
        userIntention: '', //   是 	int 	客户意向（字典分组：customer_intention）
        userLevel: '', //   是 	int 	客户等级（字典分组：customer_level）
        gateSentry: '', // 	否 	string 	门店
        addressValue: [],
        ditchTimeStr: new Date(), // 资源时间
        detailedAddress: '' // 详细地址
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        phone1: [
          { required: true, message: '请输入联系电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' }
        ],
        phone2: [{ min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' }],
        age: [
          { required: false, message: '输入年龄有误', trigger: 'blur' }
        ],
        tall: [{ required: false, message: '输入身高有误', trigger: 'blur' }],
        weight: [{ required: false, message: '输入体重有误', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择入类目', trigger: 'change' }],
        userDitch: [{ required: true, message: '请选择入线方式', trigger: 'change' }],
        platformId: [{ required: true, message: '请选择来源平台', trigger: 'change' }],
        userIntention: [{ required: true, message: '请选择客户意向', trigger: 'change' }],
        userLevel: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
        addressValue: [{ required: this.type != 'edit', message: '请选择地区', trigger: 'change' }]
      },
      dictionaries: { // 字典数据
        gender: [], // 性别
        marriage: [], // 婚否
        customer_intention: [], // 客户意向
        customer_level: [] // 客户等级
      },
      address: {
        name: '',
        phone: '',
        province: '',
        provinceId: '',
        cityId: '',
        city: '',
        area: '',
        areaId: '',
        address: ''
      },
      // 接收数据
      line: [],
      resource: 0,
      categoryList: [], // 类目列表
      platformList: [] // 平台列表
    }
  },

  created () {
    // this.$refs["form"].resetFields();
    this.commentAxios()
    // 获取字典值
    for (const type in this.dictionaries) { this.getDictionaries(type) }
    this.getPlatformList() // 获取平台列表
    this.trimAddressData() // 初始化地区数据
    this.getCategoryList()// 获取商品类目
    if (this.type == 'edit') {
      console.log(this.form, 'form')
      // this.form = Object.assign({}, this.clientObj)
      for (const item in this.clientObj) {
        this.form[item] = this.clientObj[item]
      }
      this.form.name = this.clientObj.userName
      this.form.age = this.clientObj.age ? this.clientObj.age : ''
      this.form.tall = this.clientObj.tall ? this.clientObj.tall : '' // 身高（cm）
      this.form.weight = this.clientObj.weight ? this.clientObj.weight : '' // 重量（kg）
      // this.form.userIntention = this.clientObj.userIntention ? this.clientObj.userIntention + '' : '' // 客户意向
      // this.form.userLevel = this.clientObj.userLevel ? this.clientObj.userLevel + '' : '' 	 // 客户等级
      this.form.userIntention = ''
      this.form.userLevel = ''
      this.form.platformId = ''
      this.form.userDitch = ''
      for (const item in this.form) {
        this.form[item] == null ? '' : this.form[item]
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.echoAddress()// 根据地址回显地区
    }
    var that = this
    if (this.type == 'add') {
      this.$refs['form'].clearValidate()
      this.initForm()
    }
  },
  methods: {
    // 初始化form
    initForm () {
      this.form = {
        id: '',
        userName: '',
        categoryId: '', //   是 	int 	类目id
        name: '', // 	是 	string 	名称
        phone1: '', // 	是 	string 	联系电话1
        phone2: '', // 	否 	string 	联系电话2
        birthday: '', // 	否 	string 	生日（yyyy-MM-dd）
        age: '', // 	否 	int 	  年龄
        gender: '', // 	否 	string 	性别（字典分组：gender）
        marriage: '', // 	否 	string 	婚否（字典分组：marriage）
        tall: '', // 	否 	double 	身高（cm）
        weight: '', // 	否 	double 	重量（kg）
        provinceCode: '', // 	否 	string 	省级code
        cityCode: '', // 	否 	string 	市级code
        regionCode: '', 	 // 	否 	string 	地区级code
        userDitch: '', // 	是 	string 	入线方式（来源【入线渠道设定】）
        platformId: '', 	 // 	是 	int 	来源平台id
        userIntention: '', //   是 	int 	客户意向（字典分组：customer_intention）
        userLevel: '', //   是 	int 	客户等级（字典分组：customer_level）
        gateSentry: '', // 	否 	string 	门店
        addressValue: []
      }
      this.$refs['form'].resetFields()
    },
    // 根据地址回显地区
    echoAddress () {
      this.addressOptions.find(province => {
        if (province.label == this.clientObj.provinceCode) {
          this.form.addressValue.push(province.value)
          province.children.find((city) => {
            if (city.label == this.clientObj.cityCode) {
              this.form.addressValue.push(city.value)
            }
            city.children.find((district) => {
              if (district.label == this.clientObj.regionCode) {
                this.form.addressValue.push(district.value)
              }
            })
          })
        }
      })
    },
    clickData () {
      console.log('我还没有被点击')
    },
    // 获取商品类目
    getCategoryList () {
      const params = {
        status: 'a'
      }
      this.$api.categoryQuery(params).then((res) => {
        if (res.code == 0) {
          const list = res.data.list
          // 目类只显示两级
          list.forEach((e) => {
            if (e.children) {
              e.children.forEach((ee) => {
                ee.children = null
              })
            }
          })
          this.categoryList = list
        }
      }).catch((err) => { console.log(err) })
    },
    // 获取平台列表
    getPlatformList () {
      const params = {}
      this.$api.platformDataList(params).then((res) => {
        this.platformList = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取字典数据
    getDictionaries (type) {
      if (type && this.dictionaries[type].length > 0) { return }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        this.dictionaries[type] = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 初始化地区数据
    trimAddressData () {
      // console.log("初始化地区数据", addressData)
      const arr = []
      for (const province in addressData) {
        const childrenCity = []
        for (const city in addressData[province]) {
          const childrenArea = []
          addressData[province][city].forEach((e, i) => {
            childrenArea.push({ title: '市区', label: e, value: i })
          })
          childrenCity.push({ title: '城市', label: city, children: childrenArea, value: city })
          // console.log(childrenCity.children)
        }
        arr.push({ title: '省份', label: province, children: childrenCity, value: province })
      }
      // 修改 value 值
      arr.forEach((e, i) => {
        e.value = i
        e.children.forEach((ee, ii) => {
          ee.value = ii
        })
      })
      this.addressOptions = arr
    },
    // 地区修改
    onChangeAddress (val) {
      console.log(val)
      const addressOptions = this.addressOptions
      for (let i = 0; i < val.length; i++) {
        if (i === 0) {
          this.form.provinceCode = addressOptions[val[0]].label
          console.log('省份', this.form.provinceCode)
          continue
        }
        if (i === 1) {
          this.form.cityCode = addressOptions[val[0]].children[val[1]].label
          console.log('城市', this.form.cityCode)
          continue
        }
        if (i === 2) {
          this.form.regionCode = addressOptions[val[0]].children[val[1]].children[val[2]].label
          console.log('市区', this.form.regionCode)
          continue
        }
      }
    },
    // 自动解析地址三级联动
    getAddObj () {
      this.form.address = this.form.address.replaceAll(' ', '')
      $.get(
        'http://120.24.147.235:3002/test',
        { addr: this.form.address },
        (res) => {
          const addrObj = res.message
          if (
            this.form.address.indexOf(
              addrObj.province + addrObj.city + addrObj.county
            ) === 0
          ) {
            this.updateAddr(addrObj)
          } else {
            var t = 0
            this.form.address.indexOf(addrObj.province) === 0 ? t++ : (t = t)
            this.form.address.indexOf(addrObj.city) != -1 ? t++ : (t = t)
            this.form.address.indexOf(addrObj.county) != -1 ? t++ : (t = t)
            if (t >= 2) {
              this.updateAddr(addrObj)
            }
          }
        }
      )
    },
    updateAddr (e) {
      this.form.provinceCode = e.province
      this.form.cityCode = e.city
      this.form.regionCode = e.county
      // this.form.address = this.form.address.replace(this.form.province, "");
      // this.form.address = this.form.address.replace(this.form.city, "");
      // this.form.address = this.form.address.replace(this.form.area, "");
    },
    inputPC (e) {
      if (e.length == 11) {
        this.axios.get('/order/comm/customeruser/getBelongingTo?phone=' + e, { headers: { isLoading: false }})
          .then((res) => {
            this.form.province = res.data[0].province
            this.form.city = res.data[0].city
          })

        // 根据手机号获取渠道id
        if (JSON.parse(sessionStorage.getItem('salesAuthorityId')) == '1') {
          this.axios
            .get('/order/wsCustomerChannelUser/getChannelIdByPhone?phone=' + e)
            .then((res) => {
              if (res.code == 0) {
                if (res.data) {
                  this.form.Incoming = res.data.channelId
                  this.form.name = res.data.customerName
                  this.form.ditchTime = res.data.createdTime
                } else {
                  this.form.Incoming = ''
                  this.form.name = ''
                  this.form.ditchTime = ''
                }
              }
            })
        }
      } else {
        this.form.province = ''
        this.form.city = ''
      }
    },
    //* * 普通数据请求 **//
    commentAxios () {
      console.log('333')
      // 入线方式
      this.axios.get('/order/comm/customeruser/selectCustomerditch', { headers: { isLoading: false }}).then((res) => { if (res.code == 0) { this.line = res.data } else { this.$message.error(res.message) } })
    },
    // 表单验证
    submitForm (formName) {
      if (formName === 'cancel') { return this.$emit('closeDialog', false) }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.addPermissionForm.name)
          if (this.type == 'edit') {
            this.editClient()
          } else {
            this.onCustomerAdd()
          }
          // console.log('submit!', valid, this.addPermissionForm.name);
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑
    editClient () {
      this.form.userName = this.form.name

      const data = this.form
      // data.categoryId = this.form.categoryId[this.form.categoryId.length - 1]
      this.$api.customerUpdate(data).then((res) => {
        // this.dialog.visible = false;
        // this.fetchData()
        this.$emit('closeDialog', false) // 关闭弹窗
        this.$message({ type: 'success', message: '修改成功!' })
        this.getDateList()

        console.log(res)
      }).catch((err) => {
        // this.platformForm.status = this.dictionaries.enable_status.find((e) => e.dictId == params.status || e.dictName == params.status).dictName
        // console.log(this.platformForm)
        console.log(err)
      })
    },
    // 添加
    onCustomerAdd () {
      // debugger
      const params = this.form
      // params.status = this.dictionaries.enable_status.find((e) => e.dictId == params.status || e.dictName == params.status).dictId
      params.categoryId = this.form.categoryId[this.form.categoryId.length - 1]
      params.ditchTimeStr = this.$momentTwo(params.ditchTimeStr)
      this.$api.customerAdd(params).then((res) => {
        console.log(res, 'res')
        if (res.code == 0) {
          this.$emit('closeDialog', false) // 关闭弹窗
          this.$message({ type: 'success', message: '添加成功!' })
          this.initForm()
          this.getDateList()
          console.log(res)
        }
        // this.dialog.visible = false;
        // this.fetchData()
      }).catch((err) => {
        // this.platformForm.status = this.dictionaries.enable_status.find((e) => e.dictId == params.status || e.dictName == params.status).dictName
        // console.log(this.platformForm)
        console.log(err)
      })
    }
  },
  watch: {
    dialogState: {
      handler (newVal, oldVal) {
        console.log(newVal, oldVal)
        console.log(this.type, 'type')
        if (newVal == true && this.type == 'edit') {
          this.$set
          this.getDateList()
        }
      }
    },
    type: {
      handler (newVal, oldVal) {
        console.log(newVal, oldVal)
        this.initForm()
      }
    },
    form: {
      handler (newVal, oldVal) {
        // console.log(newVal, oldVal, "form表单的")
      },
      deep: true
    }
  }
}
</script>

<style lang="scss">
.el-dialog__body{
  padding: 10px;
}
#add-customers {
  .basic {
    .content {
      padding-top: 10px !important;
      padding-bottom: 10px !important;
      .el-form {
        display: flex;
        width: 100%;
        flex-wrap: wrap;
        .el-form-item {
          //float: left;
          width: calc(50% - 15px);
          margin-bottom: 20px;
          label {
            width: 100px;
          }
          .el-form-item__content {
            width: calc(100% - 100px);
            .el-select,
            .el-cascader,
            .el-date-editor {
              width: 100%;
            }
          }
        }
      }
    }
  }
  .btn {
    display: flex;
    justify-content: right;
    margin: 10px 0 0 0;
  }
}
// 去掉input type=number时后面的上下箭头按钮
input::-webkit-outer-spin-button,input::-webkit-inner-spin-button{
  -webkit-appearance: none !important;
  -moz-appearance: none !important;
  -o-appearance: none !important;
  -ms-appearance: none !important;
  appearance: none !important;
  margin: 0;
}
input[type="number"]{
  -webkit-appearance:textfield;
  -moz-appearance:textfield;
  -o-appearance:textfield;
  -ms-appearance:textfield;
  appearance:textfield;
}

</style>
